package com.foxmail.aroundme.boring.module.news.main.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.foxmail.aroundme.boring.BuildConfig;
import com.foxmail.aroundme.boring.R;
import com.foxmail.aroundme.boring.adapter.recyclerview.NewsListAdapter;
import com.foxmail.aroundme.boring.annotation.ActivityFragmentInject;
import com.foxmail.aroundme.boring.base.view.BaseDataFragment;
import com.foxmail.aroundme.boring.bean.entry.GIFEntry;
import com.foxmail.aroundme.boring.bean.entry.JokeEntry;
import com.foxmail.aroundme.boring.bean.entry.NewsEntry;
import com.foxmail.aroundme.boring.bean.entry.WeiXinEntry;
import com.foxmail.aroundme.boring.module.news.gif.GIFListProvider;
import com.foxmail.aroundme.boring.module.news.joke.JokeListProvider;
import com.foxmail.aroundme.boring.module.news.main.presenter.INewsListPre;
import com.foxmail.aroundme.boring.module.news.main.presenter.NewsListPreImpl;
import com.foxmail.aroundme.boring.module.news.main.view.INewsListView;
import com.foxmail.aroundme.boring.module.news.newslistbean.NewsProvider;
import com.foxmail.aroundme.boring.module.news.weixin.WeiXinProvider;
import com.foxmail.aroundme.boring.module.weixinDetail.WebDetailActivity;
import com.foxmail.aroundme.boring.utils.Config;
import com.foxmail.aroundme.boring.utils.m_enum.ChannelType;
import com.foxmail.aroundme.boring.utils.m_enum.DataLoadType;
import com.foxmail.aroundme.boring.utils.m_enum.RefreshType;
import com.foxmail.aroundme.boring.utils.util.ListUtils;
import com.foxmail.aroundme.boring.weight.AutoLoadMoreRecyclerView;
import com.foxmail.aroundme.mutlitype.OnItemClickListener;
import com.foxmail.aroundme.phoenix.PullToRefreshView;
import com.socks.library.KLog;

import java.util.List;

/**
 * Created by gzl on 1/15/17.
 * 所有Fragment基础
 */
@ActivityFragmentInject(contentViewId = R.layout.newslistfragment)
public class NewsListFragment extends BaseDataFragment<INewsListPre, List> implements INewsListView<List> {

    private static final String CHANNEL_ID = "channel_id";
    private static final String CHANNEL_NAME = "channel_name";

    private String mChannelId = "";
    private String mChannelName = "";

    private AutoLoadMoreRecyclerView recyclerView;
    private PullToRefreshView pullToRefreshView;
    private NewsListAdapter newsListAdapter;

    private int AnimationTime = 3000;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mChannelId = getArguments().getString(CHANNEL_ID);
            mChannelName = getArguments().getString(CHANNEL_NAME);
        }
    }

    public static NewsListFragment newInstance(String channelId, String channelName) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CHANNEL_ID, channelId);
        bundle.putString(CHANNEL_NAME, channelName);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected void initView(View fragmentRootView) {
        mPresenter = new NewsListPreImpl(this, mChannelId);
        mPresenter.refreshData(RefreshType.EMPTY);
        recyclerView = (AutoLoadMoreRecyclerView) fragmentRootView.findViewById(R.id.news_recycler_view);
        pullToRefreshView = (PullToRefreshView) fragmentRootView.findViewById(R.id.refresh_layout);

        pullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.refreshData(RefreshType.EMPTY);
                KLog.d("start");
                pullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pullToRefreshView.setRefreshing(false);
                        mPresenter.unSubscription();
                        KLog.d("stop");
                    }
                }, AnimationTime);
            }
        });

        recyclerView.setOnLoadMoreListener(new AutoLoadMoreRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mPresenter.loadMoreData(RefreshType.EMPTY);
            }
        });


    }

    @SuppressWarnings("unchecked")
    @Override
    public void refreshSuccess(List data, @DataLoadType.LoadType int refreshType, @ChannelType.Channel final String mChannelId, boolean isCache) {
        pullToRefreshView.setRefreshing(false);

        if (recyclerView == null || getActivity() == null) {
            return;
        }
        recyclerView.notifyMoreLoaded();
        if (ListUtils.isEmpty(data)) {
            if(BuildConfig.DEBUG) {
                KLog.d("refreshSuccess data == null");
            }
            return;
        }

        Toast.makeText(getContext(), "得到" + data.size() + "条新数据" , Toast.LENGTH_SHORT).show();

        if (newsListAdapter == null) {
            newsListAdapter = new NewsListAdapter(getContext(), data);
            newsListAdapter.register(JokeEntry.class, new JokeListProvider());
            newsListAdapter.register(GIFEntry.class, new GIFListProvider());
            newsListAdapter.register(WeiXinEntry.class, new WeiXinProvider());
            newsListAdapter.register(NewsEntry.class, new NewsProvider());
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                    DividerItemDecoration.VERTICAL));
            recyclerView.setAdapter(newsListAdapter);
        } else {
            newsListAdapter.addMoreDataToTop(data);
        }

        newsListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final RecyclerView.ViewHolder holder) {

                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (newsListAdapter.isDataEmpty()) {
                            return;
                        }
                        List list = newsListAdapter.getAllData();
                        int position = holder.getLayoutPosition();

                        int size = list.size();
                        if (position < 0 || position >= size) {
                            return;
                        }

                        switch (mChannelId) {
                            case ChannelType.WeiXin:
                                WeiXinEntry weiXinEntry = (WeiXinEntry) list.get(position);
                                if (weiXinEntry == null) {
                                    return;
                                }
                                Intent weixinIntent = new Intent(getActivity(), WebDetailActivity.class);
                                weixinIntent.putExtra(Config.IntentURL, weiXinEntry.WXUrl);
                                weixinIntent.putExtra(Config.IntentTitle, weiXinEntry.WXTitle);
                                startActivity(weixinIntent);
                                break;
                            case ChannelType.GIF:

                                break;

                            case ChannelType.Joke:
                                break;

                            default:
                                NewsEntry entity = (NewsEntry) list.get(position);
                                if (entity == null) {
                                    return;
                                }
                                Intent newsIntent = new Intent(getActivity(), WebDetailActivity.class);
                                newsIntent.putExtra(Config.IntentURL, entity.newsURL);
                                newsIntent.putExtra(Config.IntentTitle, entity.newsTitle);
                                startActivity(newsIntent);
                                break;

                        }
                    }
                });

            }
        });
    }


    @Override
    public void loadMoreSuccess(List data) {
        pullToRefreshView.setRefreshing(false);
        recyclerView.notifyMoreLoaded();
        if (recyclerView == null || getActivity() == null) {
            return;
        }
        if (ListUtils.isEmpty(data)) {
            if(BuildConfig.DEBUG) {
                KLog.d("loadMoreSuccess data == null");
            }
            return;
        }


        if(BuildConfig.DEBUG) {
            KLog.d("loadMoreSuccess(BaseResponse data)");
        }

        if(newsListAdapter != null) {
            newsListAdapter.addMoreDataToBottom(data);
        }
    }

    @Override
    public void noData(@DataLoadType.LoadType int type, boolean isCache) {
        pullToRefreshView.setRefreshing(false);
        if(BuildConfig.DEBUG) {
            KLog.d("noData");
        }
        Toast.makeText(getContext(), "已经是最新数据" , Toast.LENGTH_SHORT).show();

    }

    @Override
    public void netConnectError(@DataLoadType.LoadType int type) {
        pullToRefreshView.setRefreshing(false);
        if(BuildConfig.DEBUG) {
            KLog.d("netConnectError");
        }

        Toast.makeText(getContext(), "网络似乎有点问题" , Toast.LENGTH_SHORT).show();

    }

    @Override
    public void requestError(@DataLoadType.LoadType int type) {
        pullToRefreshView.setRefreshing(false);
        if(BuildConfig.DEBUG) {
            KLog.d("requestError");
        }
    }

    @Override
    public void showProgress(@RefreshType.Refresh int type) {

    }

    @Override
    public void hideProgress() {

    }
}
